<template>
  <div>
    <div style="display: flex; align-items: flex-start; grid-gap: 20px;">
      <div style="flex: 1; width: 0;">
        <div class="card" style="flex: 1; padding: 20px; margin-bottom: 20px;">
          <div style="display: flex; align-items: center;">
            <span style="flex: 1; font-weight: bold; font-size: 20px; margin-bottom: 10px;">{{ data.series.name }}
              <span style="color: #888">({{ data.series.year }})</span> </span>
            <div>
              <span class="span-align">
                <img style="width: 40px; height: 40px; border-radius: 50%; margin-right: 5px;" :src="data.series.userAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="">
                <span style="font-size: 16px; color: pink;">{{ data.series.userName }}</span>
                <span style="font-size: 15px; color: grey">大力推荐</span>
              </span>
            </div>
          </div>
          <div style="display: flex; grid-gap: 20px; margin-bottom: 20px;">
            <img :src="data.series.cover" alt="" style="width: 250px; border-radius: 5px" />
            <div style="flex: 1; color: #666; margin: auto;">
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>导演：</strong>{{ data.series.director }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>编剧：</strong>{{ data.series.screenwriter }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>主演：</strong>{{ data.series.actors }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>类型：</strong>{{ data.series.categoryName }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>制片国家/地区：</strong>{{ data.series.country }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>语言：</strong>{{ data.series.language }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>上映日期：</strong>{{ data.series.date }}</div>
              <div style="margin-bottom: 15px; font-size: 15px;"><strong>集数：</strong>{{ data.series.episodes }}</div>
            </div>
            <div style="flex: 1; width: 150px; margin: auto; border: 2px solid #fed71a; border-radius: 10px; padding: 20px;">
              <div v-for="item in data.commentCounts" style="margin: auto auto; color: #fed71a;">
                <span style="font-size: 16px;">{{ item.commentCount ? `${item.type}: ${item.commentCount}条` : `${item.type}: 0条` }}</span>
                <el-progress style="margin-bottom: 8px;" :text-inside="true" :stroke-width="22" :percentage=item.commentCount status="warning" striped striped-flow />
              </div>
              <a href="/home" style="margin-top: 10px; color: #777; cursor: pointer; font-size: 15px;" v-if="checkMovieTop() !== -1">该电视剧目前位于电视剧排行榜第{{ checkMovieTop()+1 }}位
                <el-icon style="vertical-align: middle; color: #fed71a;" :size="20"><StarFilled /></el-icon></a>
              <a href="/home" style="margin-top: 10px; color: #777; cursor: pointer; font-size: 15px;" v-else>该电视剧未上榜，请大家积极发表长、短评为它打call吧
                <el-icon style="vertical-align: middle; color: darkgrey" :size="20"><StarFilled /></el-icon></a>
            </div>
          </div>
          <div style="font-size: 18px; color: #1967e3; margin-bottom: 10px">{{ data.series.name }}的剧情简介</div>
          <div style="color: #666; line-height: 24px;text-indent: 2rem;text-align: justify;">{{ data.series.descr }}</div>
        </div>

        <div class="card" style="padding: 20px; margin-bottom: 10px">
          <div style="font-size: 20px; color: #239113; margin-bottom: 10px">{{ data.series.name }} 的短评 <span style="font-size: 14px; color: #333">...（全部{{ data.shortTotal }}条）</span>
            <el-button style="float: right;" type="success" plain @click="addComment('短评', null, null)">写短评</el-button></div>
          <div style="border-bottom: 1px solid #eee; padding: 20px 0" v-for="item in data.shortCommentList" :key="item.id">
            <div style="display: flex; align-items: center; margin-bottom: 5px">
              <img style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px; cursor: pointer;" @click="goUserDetail(item.userId)" :src="item.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="">
              <span style="margin-right: 15px; color: mediumseagreen">{{ item.userName }}</span>
              <span style="color: #666">{{ item.time }}</span>
              <el-button style="margin-left: 20px;" type="text" @click="addComment('回复',item.id,item.userName)">回复</el-button>
            </div>

            <div style="line-height: 24px; margin-left: 34px;">{{ item.comment }}</div>
            <!--回复列表-->
            <div>
              <div v-if="item.children.length>0" style="margin: 10px 0 10px 30px; width: 90%; background-color: rgb(230, 230, 230, 0.5); padding: 15px;">
                <div v-for="index in item.children" :key="index.id" style="display: flex;">
                  <div style="margin-bottom: 5px; color: black;">
                    <img style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px;" :src="index.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="">
                  </div>
                  <div style="flex: 1;">
                    <span>{{ index.userName}}</span>
                    <span style="color: #666;"> 回复 </span>
                    <span>@{{ index.target }}</span>
                    <span style="margin-left: 15px;color: #666;">{{ index.time }}</span>
                    <div class="comment-box" style="cursor: pointer; margin-bottom: 10px; border-bottom: 1px dotted black;" @click="addComment('回复',item.id,item.userName)">{{index.comment}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <el-pagination style="margin-top: 10px;" layout="->, total, prev, pager, next" v-model:current-page="data.shortPageNum"
                         v-model:page-size="data.shortPageSize" :total="data.shortTotal" @current-change="loadShortComment" />
        </div>

        <div class="card" style="padding: 20px; margin-bottom: 10px">
          <div style="font-size: 20px; color: darkorange; margin-bottom: 10px">{{ data.series.name }} 的长评 <span style="font-size: 14px; color: #333">...（全部{{ data.longTotal }}条）</span>
            <el-button style="float: right;" type="warning" plain @click="addComment('长评', null, null)">写长评</el-button></div>
          <div style="border-bottom: 1px solid #eee; padding: 20px 0" v-for="item in data.longCommentList" :key="item.id">
            <div style="display: flex; align-items: center; margin-bottom: 5px">
              <span><img style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px; cursor: pointer;" @click="goUserDetail(item.userId)" :src="item.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt=""></span>
              <span style="margin-right: 10px; color: orange">{{ item.userName }}</span>
              <span style="color: #666">{{ item.time }}</span>
              <el-button style="margin-left: 20px;" type="text" @click="addComment('回复',item.id,item.userName)">回复</el-button>
            </div>
            <div style="line-height: 24px; color:  #666; margin-left: 34px;" class="line3" v-html="item.comment"></div>
            <div style="color: #1967e3; cursor: pointer; margin-left: 34px;" @click="showMore(item.comment)"><span>查看更多...</span></div>

            <!--回复列表-->
            <div>
              <div v-if="item.children.length>0" style="margin: 10px 0 10px 30px; width: 90%; background-color: rgb(230, 230, 230, 0.5); padding: 15px;">
                <div v-for="index in item.children" :key="index.id" style="display: flex;">
                  <div style="margin-bottom: 5px; color: black;">
                    <img style="width: 30px; height: 30px; border-radius: 50%; margin-right: 5px;" :src="index.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="">
                  </div>
                  <div style="flex: 1;">
                    <span>{{ index.userName}}</span>
                    <span style="color: #666;"> 回复 </span>
                    <span>@{{ index.target }}</span>
                    <span style="margin-left: 15px;color: #666;">{{ index.time }}</span>
                    <div class="comment-box" style="cursor: pointer; margin-bottom: 10px; border-bottom: 1px dotted black;" @click="addComment('回复',item.id,item.userName)">{{index.comment}}</div>
                  </div>
                </div>
              </div>
            </div>

          </div>
          <el-pagination style="margin-top: 10px;" layout="->, total, prev, pager, next" v-model:current-page="data.longPageNum"
                         v-model:page-size="data.longPageSize" :total="data.longTotal" @current-change="loadLongComment" />
        </div>
      </div>

      <div class="card" style="width: 300px; padding: 20px;">
        <div style="font-size: 20px; margin-bottom: 12px; color: rebeccapurple;">喜欢这部剧的人也喜欢 · · · </div>
        <div style="margin-bottom: 20px; cursor: pointer;" v-for="item in data.recommendList" :key="item.id" @click="goDetail(item.id)">
          <img :src="item.cover" alt="" style="width: 100%;" />
          <div style="margin: 5px 0; text-align: center; font-size: 17px; font-weight: bold; color: #666">{{ item.name }}</div>
        </div>
      </div>
    </div>

    <!--新增页面-->
    <el-dialog v-model="data.formVisible" title="发表评论" width="50%">
      <el-form :model="data.form" label-width="80px" style="padding-right: 20px">
        <el-form-item label="短评" prop="comment" v-if="data.form.type === '短评'">
          <el-input v-model="data.form.comment" type="textarea" autocomplete="off" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="回复" prop="comment" v-if="data.form.type === '回复'">
          <el-input v-model="data.form.comment" type="textarea" autocomplete="off" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="长评" prop="comment" v-if="data.form.type === '长评'">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.comment"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="data.formVisible=false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--显示长评-->
    <el-dialog v-model="data.formVisibleShow" title="长评" width="50%">
      <div style="line-height: 24px">
        <div class="longComment" v-html="data.comment"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisibleShow = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import router from "@/router";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import '@wangeditor/editor/dist/css/style.css'
import {onBeforeUnmount, ref, shallowRef} from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const data = reactive({
  id: router.currentRoute.value.query.id,
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  series: {},
  form: {},
  recommendList: [],
  shortCommentList: {},
  shortTotal: 0,
  shortPageNum: 1,
  shortPageSize: 3,
  longCommentList: {},
  longTotal: 0,
  longPageNum: 1,
  longPageSize: 2,
  replyCommentList: {},
  comment: '',
  formVisibleShow: false,
  formVisible: false,
  commentCounts: {},
  seriesTop: [],
})

//跳转到用户主页
const goUserDetail = (id) => {
  location.href = '/userView?id=' + id
}

//加载短评
const loadShortComment = () => {
  request.get('/seriesComment/selectPage',{
    params: {
      pageNum: data.shortPageNum,
      pageSize: data.shortPageSize,
      type: '短评',
      seriesId: data.id,
    }
  }).then(res => {
    data.shortCommentList = res.data?.list
    data.shortTotal = res.data?.total
  })
}
loadShortComment()

//加载长评
const loadLongComment = () => {
  request.get('/seriesComment/selectPage',{
    params: {
      pageNum: data.longPageNum,
      pageSize: data.longPageSize,
      type: '长评',
      seriesId: data.id,
    }
  }).then(res => {
    data.longCommentList = res.data?.list
    data.longTotal = res.data?.total
  })
}
loadLongComment()

//加载回复
const loadReplyComment = () => {
  request.get('/seriesComment/selectPage',{
    params: {
      type: '回复',
      seriesId: data.id,
    }
  }).then(res => {
    data.replyCommentList = res.data?.list
  })
}
loadReplyComment()

//查询评论数量
const loadCommentCount = () => {
  request.get('/seriesComment/countComment/' + data.id).then(res => {
    data.commentCounts = res.data
  })
}
loadCommentCount()

//添加评论
const addComment = (type,pid,target) => {
  data.form = { type: type, pid: pid, target: target }
  data.formVisible = true
}

//保存评论
const save = () => {
  if(!data.form.comment){
    ElMessage.error('评论内容不能为空')
  }else {
    data.form.seriesId = data.id
    data.form.userId = data.user.id
    request.post('/seriesComment/add', data.form).then(res => {
      if (res.code === '200') {
        data.formVisible = false
        ElMessage.success('评论成功')
        loadShortComment()
        loadLongComment()
        checkMovieTop()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}

//显示长评
const showMore = (comment) => {
  data.comment = comment
  data.formVisibleShow = true
}

//获取电视剧排行榜
const getSeriesTop = () => {
  request.get('/series/getSeriesRecommend').then(res=>{
    data.seriesTop = res.data
  })
}
getSeriesTop()

//判断电视剧是否上榜
const checkMovieTop = () => {
  const index = data.seriesTop.findIndex(series => parseInt(series.id) === parseInt(data.id))
  return index
}

/* 引入富文本样式 */
/* wangEditor5 初始化开始 */
const baseUrl = import.meta.env.VITE_BASE_URL
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* wangEditor5 初始化结束 */

const goDetail = (id) => {
  location.href = '/seriesDetail?id=' + id
}

request.get('/series/selectById/' + data.id).then(res => {
  data.series = res.data
})

request.get('/series/selectRecommend/' + data.id).then(res => {
  data.recommendList = res.data.slice(0,3)
})
</script>

